//
//  ScrollPagesContainer.m
//  MyPageControllTest
//
//  Created by apple on 11-10-11.
//  Copyright (c) 2011年 __MyCompanyName__. All rights reserved.
//

#import "ScrollPagesContainer.h"

@interface ScrollPagesContainer(private)<UIScrollViewDelegate>
- (void) initPropertyForScrollPage;
- (void) updateParams;
- (void) pageChanged:(NSInteger)page;
- (void) addPage:(UIView*)page atIndex:(NSInteger)index;
@end

@implementation ScrollPagesContainer
@synthesize currentPage;
@synthesize pageCount;
@synthesize delegate;
@synthesize scrollView;



- (id) initWithCoder:(NSCoder *)aDecoder
{
    if ((self = [super initWithCoder:aDecoder]))
    {
        [self initPropertyForScrollPage];
    }
    return self;
}

- (id)initWithFrame:(CGRect)frame
{
    if ((self = [super initWithFrame:frame]))
    {
        [self initPropertyForScrollPage];
    }
    return self;
}
-(void)dealloc
{
    [self removeObserver:self forKeyPath:@"currentPage"];
    [self removeObserver:self forKeyPath:@"pageCount"];
    [m_pageList release];
    [super dealloc];
}
-(void)addPage:(UIView *)view atIndex:(NSInteger)index
{
    CGRect frame = self.frame;
    CGRect subFrame = CGRectMake(index * frame.size.width, 0, frame.size.width, frame.size.height);
    [view setFrame:subFrame];
    [scrollView addSubview:view];
}
- (void) initPropertyForScrollPage
{
    m_isControlOutside = YES;
    CGRect frame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    scrollView = [[UIScrollView alloc] initWithFrame:frame];
    [self addSubview:scrollView];
    
    [scrollView setDelegate:self];
    scrollView.showsHorizontalScrollIndicator = NO;
    scrollView.showsVerticalScrollIndicator = NO;
    scrollView.pagingEnabled = true;
    m_pageList = [[NSMutableArray alloc] init];
    currentPage = -1;
    pageCount = 0;
    [self addObserver:self forKeyPath:@"currentPage" options:NSKeyValueObservingOptionInitial context:nil];
    [self addObserver:self forKeyPath:@"pageCount" options:NSKeyValueObservingOptionInitial context:nil];
}
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    
    if ([keyPath isEqualToString:@"currentPage"])
    {
        //currentPage changed
        [self pageChanged:currentPage];
        
    }
    else if ([keyPath isEqualToString:@"pageCount"])
    {
        //pageCount changed;
        CGSize size = CGSizeMake(pageCount * self.frame.size.width, self.frame.size.height);
        [scrollView setContentSize:size];
    
        
        
    }
}
- (void)pageChanged:(NSInteger)page
{
    if (m_isControlOutside)
    {
        CGRect frame = self.frame;
        frame.origin.x = page * frame.size.width;
        frame.origin.y = 0;
        [scrollView scrollRectToVisible:frame animated:YES];
    }
    
    
    if ([delegate respondsToSelector:@selector(scrollPagesContainerDidChangePage:page:)])
    {
        [delegate scrollPagesContainerDidChangePage:self page:currentPage];
        
        
    }
    UIView* pageView = Nil;
    for (NSInteger i = page - 1; i <= page + 1; i++)
    {
        if (i >= 0 && i < pageCount)
        {
            if (i < m_pageList.count)
            {
                pageView = [m_pageList objectAtIndex:i];
            }
            if (pageView == Nil)
            {
                if ([delegate respondsToSelector:@selector(scrollPagesContainerLoadPage:forIndex:)])
                {
                    pageView = [delegate scrollPagesContainerLoadPage:self forIndex:i];
                    [m_pageList insertObject:pageView atIndex:i];
                }
                
            }
            if (pageView.superview == Nil)
            {
                [self addPage:pageView atIndex:i];
            }
            pageView = Nil;
        }

//    if ([delegate respondsToSelector:@selector(scrollPagesContainerLoadPage:forIndex:)])
//    {
//        
//        for (NSInteger i = page - 1; i <= page + 1; i++)
//        {
//            if (i >= 0 && i < pageCount)
//            {
//                if (i < m_pageList.count)
//                {
//                   pageView = [m_pageList objectAtIndex:i];
//                }
//                if (pageView == Nil)
//                {
//                    pageView = [delegate scrollPagesContainerLoadPage:self forIndex:i];
//                    [m_pageList insertObject:pageView atIndex:i];
//                }
//                if (pageView.superview == Nil)
//                {
//                    [self addPage:pageView atIndex:i];
//                }
//                pageView = Nil;
//            }
//        
//        }
        
        
    }
    //remove form superview the page - 2;
    NSInteger tmpPage = page - 2;
    if (tmpPage >= 0 && tmpPage < pageCount && tmpPage < m_pageList.count)
    {
        pageView = [m_pageList objectAtIndex:tmpPage];
        if (pageView.superview != Nil)
        {
            [pageView removeFromSuperview];
        }
    }
    //remove form superview the page + 2;
    tmpPage = page + 2;
    if (tmpPage >= 0 && tmpPage < pageCount && tmpPage < m_pageList.count)
    {
        pageView = [m_pageList objectAtIndex:tmpPage];
        if (pageView.superview != Nil)
        {
            [pageView removeFromSuperview];
        }
    }
}
/**
 *   here is the delegate function
 *
 *
 */
- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    
    if (m_isControlOutside)
    {
        return;
    }
    
    CGFloat pageWidth = self.scrollView.frame.size.width;
    
    int page = floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
    
    if (page != currentPage)
    {
        self.currentPage = page;
    }
    //send delegate;
    if ([delegate respondsToSelector:@selector(scrollPagesContainerDidScroll:)])
    {
        [delegate performSelector:@selector(scrollPagesContainerDidScroll:) withObject:self];
    }
    
    
}
-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView
{
    m_isControlOutside = NO;
}
//-(void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
//{
//    m_isControlOutside = YES;
//    NSLog(@"end1");
//}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    m_isControlOutside = YES;
}
//-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(CGPoint *)targetContentOffset
//{
//    m_animating = NO;
//    NSLog(@"end1");
//}
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
    if ([delegate respondsToSelector:@selector(scrollPagesContainerDidFinishedAnimation:)])
    {
        [delegate performSelector:@selector(scrollPagesContainerDidFinishedAnimation:) withObject:self];
    }
}
@end

          



